package org.ting.j20250110_gobang.game;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.ting.j20250110_gobang.model.User;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

@Component
public class Matcher {
    //每个匹配队列代表不同的段位,这里约定每一千分为一个段位
    private ArrayList<Queue<User>> matchQueueList = new ArrayList<>();
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private OnlineUserManager onlineUserManager;
    @Autowired
    private RoomManager roomManager;
    public Matcher() {
        //暂定三个段位
        for(int i = 0; i < 3; i++) {
            matchQueueList.add(new LinkedList<>());
        }

        //每个队列创建一个线程扫描完成匹配功能
        for(Queue<User> q : matchQueueList) {
            Thread t = new Thread(()->{
                while(true) {
                    //调用handlerMatch()完成匹配功能
                    handlerMatch(q);
                }
            });
            t.start();
        }
    }
    public void add(User user) {
        int index = Math.min(user.getScore() / 3, 2);
        Queue<User> queue = matchQueueList.get(index);
        //对操作的队列加锁保证线程安全
        synchronized (queue) {
            queue.offer(user);
            queue.notify();
        }
        System.out.println("用户 " + user.getUsername() + " 加入了 " + index + "号 队列");
    }

    public void remove(User user) {
        int index = Math.min(user.getScore() / 3, 2);
        Queue<User> queue = matchQueueList.get(index);
        synchronized (queue) {
            queue.remove(user);
        }
        System.out.println("把用户 " + user.getUsername() + " 从 " + index + "号 队列中删除");
    }

    public void handlerMatch(Queue<User> matchQueue) {
        try {
            //对操作的队列加锁保证线程安全
            synchronized (matchQueue) {
                //1.检测队列中是否有两个元素
                while(matchQueue.size() < 2) {
                    matchQueue.wait();
                }

                //2.从队列中取出两个玩家
                User user1 = matchQueue.poll();
                User user2 = matchQueue.poll();

                //3.获取到两个玩家的会话信息
                WebSocketSession session1 = onlineUserManager.getFromHall(user1.getUserId());
                WebSocketSession session2 = onlineUserManager.getFromHall(user2.getUserId());

                System.out.println("匹配成功，" + user1.getUsername() + "," + user2.getUsername() + "正在进入游戏房间");

                //4.把两个玩家放到一个游戏房间中
                Room room = new Room();
                roomManager.add(room.getRoomId(), room, user1.getUserId(), user2.getUserId());

                //5.给用户返回匹配成功的响应
                MatchResponse response = new MatchResponse();
                response.setOk(true);
                response.setMessage("success");
                String json = objectMapper.writeValueAsString(response);
                session1.sendMessage(new TextMessage(json));
                session2.sendMessage(new TextMessage(json));
            }
        }catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

    }
}
